const app = getApp();

function request(options) {
  const baseURL = app.globalData.baseUrl || "http://localhost:8080";
  const timeout = options.timeout || 600000;

  const defaultHeader = {
    "Content-Type": options.header?.["Content-Type"] || "application/json",
  };
  
  const token = wx.getStorageSync("token");
  if (token) {
    defaultHeader.token = token;
  }
  
  // 添加用户ID
  const userId = wx.getStorageSync('userId') || app.globalData.userId;
  if (userId) {
    defaultHeader['X-User-ID'] = userId;
  }

  return new Promise((resolve, reject) => {
    const requestTask = wx.request({
      url: baseURL + options.url,
      method: options.method || "GET",
      data: options.data || {},
      header: defaultHeader,
      timeout: timeout,
      success: (resp) => {
        const backendData = resp.data;
        if (backendData?.code === 1006) {
          wx.showToast({ title: "登录失效", icon: "none" });
          wx.removeStorageSync("token");
          app.globalData.hasLogin = false;
          app.redirectToLoginIfNeeded();
          reject(new Error("登录失效"));
          return;
        }
        resolve(backendData);
      },
      fail: (error) => {
        wx.showToast({ title: "网络请求失败，请重试", icon: "none" });
        reject(error);
      },
      complete: () => {
      }
    });
    
    setTimeout(() => {
      if (requestTask) {
        requestTask.abort();
        wx.showToast({ title: "请求超时，请重试", icon: "none" });
        reject(new Error("请求超时"));
      }
    }, timeout);
  });
}
// 增加 get/post/put/del 方法
request.get = (url, data) => request({ url, data, method: "GET" });
request.post = (url, data) => request({ url, data, method: "POST" });
request.put = (url, data) => request({ url, data, method: "PUT" });
request.del = (url, data) => request({ url, data, method: "DELETE" });

// 添加便捷方法（保持第一个版本不变，只添加这些方法）
request.get = (url, data) => request({ url, method: 'GET', data });
request.post = (url, data) => request({ url, method: 'POST', data });
request.put = (url, data) => request({ url, method: 'PUT', data });
request.delete = (url, data) => request({ url, method: 'DELETE', data });

module.exports = request;